package edu.gxmzu.task.handler;

import edu.gxmzu.task.utils.Result;
import edu.gxmzu.task.utils.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;

// 认证异常处理器
@Component
@Slf4j
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("认证时出现 {} 异常: {}", authException.getClass().getSimpleName(), authException.getMessage());  // 打印到日志，便于调试
        // 响应, 获取异常消息并返回

        // 出现认证信息不完全，过滤器抛出的BadCredentialsException被包装成了InsufficientAuthenticationException
        // "Full authentication is required to access this resource"

        if (authException instanceof UsernameNotFoundException || authException instanceof BadCredentialsException) {
            WebUtil.renderString(response, Result.unauthorized(authException.getMessage()));
        } else {
            // 处理其他认证异常
            if (!Objects.isNull(request.getAttribute("errorMessage"))) WebUtil.renderString(response, Result.unauthorized(request.getAttribute("errorMessage").toString()));
            else WebUtil.renderString(response, Result.unauthorized("认证失败，请尝试重新登录！"));
        }
    }
}
